package com.jingtai.platform.advice;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jingtai.common.constants.RedisConstant;
import com.jingtai.common.utils.ResponseUtil;
import com.jingtai.common.webfacade.error.ErrorEnum;
import com.jingtai.common.webfacade.response.ResponseMsg;
import com.jingtai.platform.util.JwtTokenUtils;
import com.jingtai.platform.util.ResultUtil;
import io.swagger.annotations.ApiOperationSupport;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("ALL")
@Component
@Aspect
public class WebAspect {


    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.expiration}")
    private Integer expiration;

    @Value("${jwt.tokenStart}")
    private String tokenStart;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 切入点
     * 匹配com.example.controller1包及其子包下的所有类的所有方法
     */
    @Pointcut("execution( * com.jingtai.platform.controller.*.*.aop*(..))")
    public void executePackage() {
    }

    /**
     * 环绕通知：
     * 环绕通知非常强大，可以决定目标方法是否执行，什么时候执行，执行时是否需要替换方法参数，执行完毕是否需要替换返回值。
     * 环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型
     */
    @Around("executePackage()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String requestHeader = request.getHeader(tokenHeader);
        Long userId = null;
        String authToken = null;
        String headerStart = tokenStart + " ";
        if (requestHeader != null && requestHeader.startsWith(headerStart)) {
            authToken = requestHeader.substring(headerStart.length());
            try {
                userId = jwtTokenUtils.getUserIdFromToken(authToken);
            } catch (Exception e) {
                return new ResultUtil(ErrorEnum.TOKEN_INVALID.getErrorDescription());
            }
        }else{
            return new ResultUtil(ErrorEnum.TOKEN_INVALID.getErrorDescription());
        }

        if (ObjectUtil.isNotEmpty(userId)) {
            String tokenFromRedis = redisTemplate.opsForValue().get(RedisConstant.TOKEN_LOGIN_PLATFORM_PRE_KEY + userId);
            if (StringUtils.isNotBlank(tokenFromRedis)) {
                JSONObject jsonObject = JSONObject.parseObject(tokenFromRedis);
                String username = jwtTokenUtils.getUsernameFromToken(authToken);
                String token = jwtTokenUtils.getTokenFromRedis(jsonObject);
                //如果长时间未操作result为null
                if (StringUtils.isNotBlank(token)) {

                    //保证用户单终端登录
                    if (StringUtils.equals(authToken, token)) {
                        //校验token的有效性
                        if (jwtTokenUtils.validateToken(authToken, username)) {
                            redisTemplate.opsForValue().set(RedisConstant.TOKEN_LOGIN_PLATFORM_PRE_KEY + userId, tokenFromRedis, expiration, TimeUnit.HOURS);
                            return (ResultUtil) proceedingJoinPoint.proceed();
                        }
                    }
                }
            }
        }
        return new ResultUtil(ErrorEnum.TOKEN_INVALID.getErrorDescription());
    }

}